﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using mogco.Structs;
using System.Collections;
using FreeImageAPI.Metadata;
using FreeImageAPI;
using mogco.Visuals;
using System.Resources;

namespace mogco
{
    public partial class Form1 : Form
    {

        # region Forms
        /// <summary>
        /// визуальный каркас для плагинов
        /// </summary>
        OnlineGetterPluginTemplate ogpt;
        ProcessWindow prWindow;
        # endregion

        CMPMainWorker cmpMainWorker;

        public static List<string> files = new List<string>();    
        private MDM_EXIF_MAIN[] exifs = new MDM_EXIF_MAIN[4];

        private FolderBrowserDialog selectDir  = new FolderBrowserDialog();
        private OpenFileDialog selectFile = new OpenFileDialog();

        // position for each control;
        Size pos = new Size(10,10);

        private BackgroundWorker backgroundWorker1 = new BackgroundWorker();

        

        private string OpenDirName;

        public Form1()
        {
            InitializeComponent();
            // Инициализаци программы
            // TODO: вынести в отдельную функцию
            prWindow = new ProcessWindow();
            cmpMainWorker = new CMPMainWorker();
            cmpMainWorker.UseDirectoryTree = Settings.xml.UseDirectoryTree;
            Program.pluginServices.Logger = Logger.txtLogger;
            cmpMainWorker.LoadPlugins();
            // Adding plugins button to "Online" tab
            int plugin_button_width = 100;
            int button_top = 20;
            Logger.Initialize();
            foreach (Interface.IPlugin plugin in cmpMainWorker.Plugins.Values)
            {
                Button plugin_button = new Button();
                plugin_button.Text = plugin.Name;
                plugin_button.Width = plugin_button_width;
                plugin_button.Click += new EventHandler(plugin_button_Click);
                tabPage3.Controls.Add(plugin_button);
                //pluginView.Rows.Add(plugin.Name, plugin_button);
                //pluginView.Rows.Add("lalal", "lala");
                button_top += 25;
            }
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            pictList1.SelectedPictureChanged += new PictList.SelectedPictureChangedHandler(pictList1_PictureChanged);
            pictList1.AddSlots();
        }



        private void openDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /* Clear, if reopen */
            if (files.Count != 0)
                files.Clear();

            if (Settings.xml.PreviousPath != null && Settings.xml.PreviousPath.Length != 0)
                selectDir.SelectedPath = Settings.xml.PreviousPath;
            DialogResult dresult = selectDir.ShowDialog();

            if (DialogResult.OK == dresult)
            {
                OpenDirName = selectDir.SelectedPath;
                toolStripStatusLabel1.Text = OpenDirName;
            }
            if (null != OpenDirName)
            {
                //cmpMainWorker.GetDirectoryTree(OpenDirName);
                cmpMainWorker.RootDirectory = new DirectoryInfo(OpenDirName);
                cmpMainWorker.GRFilesByPath(OpenDirName, ref files);
                Settings.xml.PreviousPath = OpenDirName;
                Settings.Save();
            }
            this.OpenFiles();
        }

        private void OpenFiles()
        {
            if (files.Count != 0)
            {
                pictList1.AddFiles(files);
                label6.Text = files.Count.ToString();
                this.button1.Enabled = true;
                this.label7.Text = Settings.xml.Resolution.Y.ToString() + "x" + Settings.xml.Resolution.X.ToString();
                this.label7.Visible = true;
            }
            else
            {
                pictList1.Clear();
            }
            this.Refresh();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void convertToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (files != null && files.Count != 0)
                backgroundWorker1.RunWorkerAsync();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void statusStrip1_SizeChanged(object sender, EventArgs e)
        {
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsWindow _sWindow = new SettingsWindow(cmpMainWorker);
            _sWindow.ShowDialog();
            // Update interface after changes
            if (this.label7.Visible)
                label7.Text = Settings.xml.Resolution.ToString();
        }

        private void pictList1_PictureChanged(object sender, mogco.PictList.SelectedPictureChangedArgs e)
        {
            if (e.file.Length != 0)
                UpdateInfoInForm(e.file);
        }

        public void UpdateInfoInForm(string file)
        {
            ImageWorker _imworker = new ImageWorker();
            FileInfo fInfo = new FileInfo(file);
            BITMAPINFOHEADER header = _imworker.GetBitmapProps(file);
            //dataGridView1.Rows.Clear();
            //dataGridView1.Rows.Add("Name", fInfo.Name);
            //dataGridView1.Rows.Add("Width", header.biWidth.ToString());
            //dataGridView1.Rows.Add("Height", header.biHeight.ToString());
            //dataGridView1.Rows.Add("Date", "XX-DATE");
            //this.label1.Text = header.biWidth.ToString(); this.label1.Visible = true;
            //this.label2.Text = header.biHeight.ToString(); this.label2.Visible = true;
            FileInfo finfo = new FileInfo(file);
            //this.label9.Text = finfo.Name; this.label9.Visible = true;
            //this.label4.Text = exif.DateTimeOriginal.ToString(); this.label4.Visible = true;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (prWindow.IsDisposed)
                prWindow = new ProcessWindow();
            prWindow.Show();
            prWindow.SetProgressBound(0, files.Count-1);
            prWindow.SetProgress(0);
            this.button1.Enabled = false;
            button2.Enabled = true;
            backgroundWorker1.RunWorkerAsync();
        }


        private void StartConvert(BackgroundWorker worker)
        {
                int i = 0;
                ImageWorker _imWorker = new ImageWorker();
                // Create new CMPMainWorker, because StartConvert runs in other thread
                //CMPMainWorker _mpWorker = new CMPMainWorker();
                foreach (var _file in files)
                {
                    if (backgroundWorker1.CancellationPending == true) // если нажать кнопку Stop - выход
                    {
                        break;
                    }
                    string _savepath = cmpMainWorker.FormNewPathes(_file, Settings.xml.SavePath, Settings.xml.FilesMask);  // сформировать путь для сохранения
                    if (!File.Exists(_savepath) || Settings.xml.RewriteExistsFiles)         // проверить, можно ли перезаписать файл
                    {
                        if (Settings.xml.RewriteExistsFiles)
                        {
                            prWindow.WriteMessage("Rewriting:" + _file);
                        }
                        else
                            prWindow.WriteMessage("Converting image: " + _file);
                        prWindow.WriteMessage("Saving in: " + _savepath);
                        try
                        {
                            _imWorker.ConvertImage(_file, _savepath);
                        }
                        catch (Exception e)
                        {
                            prWindow.WriteMessage(e.Message);
                            Logger.txtLogger.WriteMessage("Error occured while converting image" + e.ToString());
                        }
                    }
                    else
                    {
                        prWindow.WriteMessage("File exists. Skip file.");
                    }
                    worker.ReportProgress(i);
                    i++;
                }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            prWindow.SetProgress(e.ProgressPercentage);
        }

        private void backgroundWorker1_RunWorkerCompleted(object snder, RunWorkerCompletedEventArgs e)
        {
            //prWindow.SetProgress(0);
            this.button1.Enabled = true;
            this.button2.Enabled = false;
            prWindow.SetCloseState(true);
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker _worker = sender as BackgroundWorker;
            StartConvert(_worker);
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.WorkerSupportsCancellation == true && backgroundWorker1.IsBusy)
            {
                backgroundWorker1.CancelAsync();
            }
        }

        private void plugin_button_Click(object sender, EventArgs e)
        {
            Button button_sender = sender as Button;
            Interface.IPlugin plugin = (Interface.IPlugin)cmpMainWorker.Plugins[button_sender.Text];
            try
            {
                ogpt = new OnlineGetterPluginTemplate(plugin);
                ogpt.Show();
                ogpt = null;
            }
            catch (Exception ex)
            {
                Logger.txtLogger.WriteMessage("Error in plugin " + plugin.Name + ". " + ex.ToString());
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            pictList1.Dispose();
        }

    }
}
